package bp;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.jws.WebMethod;
import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.persistence.NoResultException;
import javax.persistence.Query;

import models.Insurance;
import models.InsuranceCancel;
import models.InsuranceReturn;
import models.Order;
import models.Organization;
import models.Scheduleprice;
import models.Station;
import models.TicketCancel;
import models.Ticketreturn;
import models.Ticketsell;
import net.sf.json.JSONObject;
import param.cancelticket.Cancelrequest;
import param.cancelticket.Cancelresponse;
import param.changeticketno.Changeticketnorequest;
import param.lock.Lockrequest;
import param.lock.Lockresponse;
import param.lock.Lockticketrequestinfo;
import param.lock.Lockticketresponseinfo;
import param.messagesvo.CancelTicketVo;
import param.messagesvo.CancelUnknownVo;
import param.messagesvo.ChangeTicketnoVo;
import param.messagesvo.LockVo;
import param.messagesvo.ReturnTicketSuccessVo;
import param.messagesvo.ReturnUnknownSuccessVo;
import param.messagesvo.ReturninsuranceVO;
import param.messagesvo.SellSuccessVo;
import param.messagesvo.SellUnknownVo;
import param.messagesvo.UnlockVo;
import param.orderquery.Orderqueryrequest;
import param.orderquery.Orderqueryresponse;
import param.orderquery.Orderticket;
import param.pub.Publicrequest;
import param.pub.Publicresponse;
import param.returninsurance.Cancelinsurancerequest;
import param.returnticket.Returnrequest;
import param.returnticket.Returnresponse;
import param.returnunknown.ReturnUnknownrequest;
import param.sell.CenterSellRequest;
import param.sell.Sellrequest;
import param.sell.Sellresponse;
import param.sell.SellticketIn;
import param.sell.Sellticketout;
import param.unlock.Unlockrequest;
import play.Logger;
import play.db.jpa.JPA;
import service.InvokeService;
import utils.CommonUtils;
import utils.CommonUtils.TableIndex;
import utils.DateUtils;
import utils.ErrorMailUtil;
import utils.FNVHash;
import utils.JsonUtil;
import utils.LogUtil;
import utils.PublicXmlUtil;
import utils.XmlUtil;
import utils.encode.RandomTicketNo;

public class NetSaleBP {

	@SuppressWarnings("unused")
	public boolean lock(String jsonString) {
		Logger.log4j.info(new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date())+"消费Lock消息"+jsonString);
		LockVo lockvo = null;
		Lockrequest lockreq = null;
		Lockresponse lockres = null;
		// lockres.setPublicresponse(PublicXmlUtil.newPublicresponse());

		try {
			if(JPA.em().getTransaction().isActive()){
				JPA.em().getTransaction().commit();
			}
			try {
				lockvo = (LockVo) JsonUtil.readJson2Entity(jsonString, LockVo.class);
			} catch (Exception e) {
				LogUtil.logerror("锁位请求格式错误,XML转换失败" + jsonString, e);
				ErrorMailUtil.sendMail("BLOCK0001", e);
				// lockres.getPublicresponse().setResultcode("NALOCK1000");
				// lockres.getPublicresponse().setResultmsg("请求格式错误");
				return false;
			}

			lockreq = lockvo.getRequestcontent();
			lockres = lockvo.getResponsecontent();

			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			Date departdate = null;
			try {
				departdate = sdf.parse(lockreq.getDepartdate());
			} catch (Exception e) {
				LogUtil.logerror("发车日期格式错误" + jsonString, e);
				ErrorMailUtil.sendMail("BLOCK0001", e);
				return false;
			}
			Organization sellorg = queryOrganizationByCode(lockreq.getPublicrequest().getAskorgcode());
			if (sellorg == null) {
				LogUtil.logerror(lockreq.getPublicrequest().getAskorgcode() + "找不到机构信息");
				ErrorMailUtil.sendMail("BLOCK0001", lockreq.getPublicrequest().getAskorgcode() + "找不到机构信息");
				return false;
			}

			Organization departorg = queryOrganizationByCode(lockreq.getPublicrequest().getTargetorgcode());
			if (departorg == null) {
				LogUtil.logerror(lockreq.getPublicrequest().getTargetorgcode() + "找不到机构信息");
				ErrorMailUtil.sendMail("BLOCK0001", lockreq.getPublicrequest().getTargetorgcode() + "找不到机构信息");
				return false;
			}

			Station station = null;
			String sql = "select s from Station s where s.orgcode='" + departorg.code + "'" + "and s.code='" + lockreq.getReachstationcode() + "'";
			Query queryst = JPA.em().createQuery(sql);
			try {
				station = (Station) queryst.getSingleResult();
			} catch (Exception e) {
				LogUtil.logerror("不存在orgcode=" + departorg.code + "code=" + lockreq.getReachstationcode() + "到站编码");
				ErrorMailUtil.sendMail("BLOCK0001", "不存在orgcode=" + departorg.code + "code=" + lockreq.getReachstationcode() + "到站编码");
				return false;

			}

			String ORDER_SQL = "SELECT o FROM Order o WHERE o.orderno='" + lockreq.getOrderno() + "'";
			Query queryor = JPA.em().createQuery(ORDER_SQL);
			Order order = null;
			try {
				order = (Order) queryor.getSingleResult();
			} catch (Exception e) {
				order = new Order();
				order.id = CommonUtils.GetPKID(TableIndex.orders);
				order.orderno = lockreq.getOrderno();
			}
			if (!JPA.em().getTransaction().isActive()) {
				JPA.em().getTransaction().begin();
			}
			StringBuilder amounts = new StringBuilder();//车票金额列表
			BigDecimal amount = new BigDecimal(0);//订单总金额
			StringBuilder ticketids = new StringBuilder();
			StringBuilder passengernames = new StringBuilder();//乘客姓名
			StringBuilder passengerphones = new StringBuilder();//乘客电话号码
			StringBuilder certificatenos = new StringBuilder();//乘客证件号
			StringBuilder tickettypes = new StringBuilder();//车票类型
			StringBuilder seatnos = new StringBuilder();//座位号
			for(Lockticketresponseinfo resticket : lockres.getTickets()){
				amount = amount.add(resticket.getPrice());
				ticketids.append(resticket.getNetticketid()).append(",");
				seatnos.append(resticket.getSeatno()).append(",");
			}
			for(Lockticketrequestinfo reqticket : lockreq.getTickets()){
				amounts.append(reqticket.getPrice()).append(",");
				passengernames.append(reqticket.getCustomername()).append(",");
				passengerphones.append(reqticket.getPhone()).append(",");
				certificatenos.append(reqticket.getCertificateno()).append(",");
				tickettypes.append(reqticket.getTickettype()).append(",");
				
			}
			order.amount = amount.doubleValue();
			order.amounts = amounts.toString().substring(0, amounts.toString().length()-1);
			order.passengernames = passengernames.toString().substring(0, passengernames.toString().length()-1);
			order.passengerphones = passengerphones.toString().substring(0, passengerphones.toString().length()-1);
			order.certificatenos = certificatenos.toString().substring(0, certificatenos.toString().length()-1);
			order.tickettypes = tickettypes.toString().substring(0, tickettypes.toString().length()-1);
			order.seatnos = seatnos.toString().substring(0, seatnos.toString().length()-1);
			order.netticketids = ticketids.toString().substring(0, ticketids.toString().length()-1);
			order.createby = 0;
			order.createtime = new Date();
			order.departdate = departdate;
			order.departorgcode = departorg.code;
			order.departorgname = departorg.name;
			order.departtime = lockreq.getDeparttime();
			order.lockdelay = lockreq.getLockdelay();
			order.locktime = new Date();
			order.reachstationcode = lockreq.getReachstationcode();
			order.reachstationname = station.name;
			order.schedulecode = lockreq.getSchedulecode();
			order.seatnum = lockreq.getSeatnum();
			order.seattype = lockreq.getSeattype();
			order.sellorgcode = sellorg.code;
			order.sellorgname = sellorg.name;
			order.sellway = "7";// 网上售票
			order.updateby = 0;
			order.status = "0";// 新建立
			order.updatetime = new Date();
			order.save();
			JPA.em().getTransaction().commit();
			finishMsg(jsonString ,new Date());
			return true;

		} catch (Exception e) {
			LogUtil.logerror("锁位失败：未知异常" + jsonString, e);
			if (!JPA.em().getTransaction().isActive()) {//开启事务
				JPA.em().getTransaction().begin();
			}
			JPA.em().getTransaction().rollback();
			ErrorMailUtil.sendMail("BLOCK0001", e);
			// lockres.getPublicresponse().setResultcode("NALOCK1010");
			// lockres.getPublicresponse().setResultmsg("锁位失败：未知异常");
			return false;
		}
	}

	public boolean unlock(String jsonString) {
		UnlockVo unlockvo = null;
		Unlockrequest unlockreq = null;
		// Unlockresponse unlockres = new Unlockresponse();
		// unlockres.setPublicresponse(PublicXmlUtil.newPublicresponse());
		try {
			if(JPA.em().getTransaction().isActive()){
				JPA.em().getTransaction().commit();
			}
			try {
				unlockvo = (UnlockVo) JsonUtil.readJson2Entity(jsonString, UnlockVo.class);
			} catch (Exception e) {
				LogUtil.logerror("网站请求格式错误,XML转换失败" + jsonString, e);
				ErrorMailUtil.sendMail("BUNLO0001", e);
				// unlockres.getPublicresponse().setResultcode("NAULCK1000");
				// unlockres.getPublicresponse().setResultmsg("网站请求格式错误");
				return false;
			}

			unlockreq = unlockvo.getRequestcontent();
			// String resultXml = PublicXmlUtil.toXml(unlockres);
			// if (unlockres != null && unlockres.getPublicresponse() != null &&
			// "0000".equals(unlockres.getPublicresponse().getResultcode())) {
			// 车站解锁成功，更新中心的订单状态
			String sql = "select o from Order o where orderno='" + unlockreq.getOrderno() + "'";
			Query queryorder = JPA.em().createQuery(sql, Order.class);
			Order order = null;
			try {
				order = (Order)queryorder.getSingleResult();
			} catch (Exception e) {
				LogUtil.logqurey(queryorder);
				LogUtil.logerror("未找到订单号为" + unlockreq.getOrderno() + "订单信息", e);
				ErrorMailUtil.sendMail("BUNLO0001", e);
			}
			if (order != null) {
				if (!JPA.em().getTransaction().isActive()) {
					JPA.em().getTransaction().begin();
				}
				if (order.seatnum == 1) {
					order.seatnum = 0;
					order.status = "2";
					order.amount = 0.0;
					order.amounts = "";
				} else if ("".equals(unlockreq.getNetticketid()) || unlockreq.getNetticketid() == null){
					order.seatnum = 0;
					order.status = "2";
					order.amount = 0.0;
					order.amounts = "";
				} else {
					order.seatnum = order.seatnum - 1;
					order.status = "0";
					if(order.amounts==null || "".equals(order.amounts) || order.netticketids==null || "".equals(order.netticketids)){
						//
					}else{
						String[] prices = order.amounts.split(","); 
						String[] netticketids = order.netticketids.split(",");
						StringBuilder amounts = new StringBuilder();
						StringBuilder ticketids = new StringBuilder();
						for(int i=0;i<netticketids.length;i++){
							if(netticketids[i].equals(unlockreq.getNetticketid())){
								order.amount -= new Double(prices[i]);
							}else{
								amounts.append(prices[i]).append(",");
								ticketids.append(netticketids[i]).append(",");
							}
						}
					}
				}
				order.updatetime = new Date();
				order.save();
				JPA.em().getTransaction().commit();
			}
			finishMsg(jsonString ,new Date());
			return true;
		} catch (Exception e) {
			if (!JPA.em().getTransaction().isActive()) {//开启事务
				JPA.em().getTransaction().begin();
			}
			JPA.em().getTransaction().rollback();
			// unlockres.getPublicresponse().setResultcode("NAULCK1010");
			// unlockres.getPublicresponse().setResultmsg("解锁失败：未知异常");
			LogUtil.logerror("解锁失败：未知异常" + jsonString, e);
			ErrorMailUtil.sendMail("BUNLO0001", e);
			return false;
		}
	}

	public boolean sell(String jsonString) {
		Logger.log4j.info(new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date())+"消费Sell消息"+jsonString);
		SellSuccessVo sellsuccessvo = null;
		Sellrequest sellreq = null;
		Sellresponse sellres = null;
		// sellres.setPublicresponse(PublicXmlUtil.newPublicresponse());

		try {
			if(JPA.em().getTransaction().isActive()){
				JPA.em().getTransaction().commit();
			}
			try {
				sellsuccessvo = (SellSuccessVo) JsonUtil.readJson2Entity(jsonString, SellSuccessVo.class);
			} catch (Exception e) {
				LogUtil.logerror("网站请求格式错误,XML转换失败" + jsonString);
				// sellres.getPublicresponse().setResultcode("NASELL1000");
				// sellres.getPublicresponse().setResultmsg("网站请求格式错误");
				ErrorMailUtil.sendMail("BSELL0001", e);
				return false;
			}

			sellreq = sellsuccessvo.getRequestcontent();
			sellres = sellsuccessvo.getResponsecontent();
			StringBuilder sb = new StringBuilder();
			for(SellticketIn si : sellreq.getTickets()){
				sb.append("'").append(si.getNetticketid()).append("',");
			}
			String netticketids = sb.toString().substring(0, sb.toString().length()-1);
			String SQL = "SELECT * FROM ticketsell  WHERE netticketid in ("+netticketids+")";
			List<Ticketsell> ticketsells = JPA.em().createNativeQuery(SQL, Ticketsell.class).getResultList();
			if(ticketsells.size()>0 && ticketsells.size() == sellreq.getTickets().size()){
				return true;
			}
			Organization departorg = queryOrganizationByCode(sellreq.getPublicrequest().getTargetorgcode());
			if (departorg == null) {
				LogUtil.logerror(sellreq.getPublicrequest().getTargetorgcode() + "找不到机构信息");
				ErrorMailUtil.sendMail("BSELL0001", sellreq.getPublicrequest().getTargetorgcode() + "找不到机构信息");
				return false;
			}

			String sql = "select o from Station o where o.code='" + sellreq.getReachstationcode() + "' and o.orgcode='" + departorg.code + "'";
			Query queryst = JPA.em().createQuery(sql);
			Station reachstation = null;
			try {
				reachstation = (Station) queryst.getSingleResult();
			} catch (Exception e) {
				// 不存在该到站的编码
				LogUtil.logerror("不存在orgcode=" + departorg.code + "code=" + sellreq.getReachstationcode() + "到站编码");
				ErrorMailUtil.sendMail("BSELL0001", e);
				return false;
			}

			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			Date departdate;
			try {
				departdate = sdf.parse(sellreq.getDepartdate());
			} catch (ParseException e1) {
				LogUtil.logerror("发车日期格式转换失败");
				ErrorMailUtil.sendMail("BSELL0001", e1);
				return false;
			}

			String reachstationcode = sellreq.getReachstationcode();
			String SPLIST_SQL = "select s from Scheduleprice s where s.departdate=:departdate and s.orgcode=:orgcode and s.schedulecode=:schedulecode and s.reachstationcode=:reachstationcode and s.seattype=:seattype";
			Query querysp = JPA.em().createQuery(SPLIST_SQL);
			querysp.setParameter("departdate", departdate);
			querysp.setParameter("orgcode", departorg.code);
			querysp.setParameter("schedulecode", sellreq.getSchedulecode());
			querysp.setParameter("reachstationcode", reachstationcode);
			querysp.setParameter("seattype", sellreq.getSeattype());
			Scheduleprice sp = null;
			try {
				sp = (Scheduleprice) querysp.getSingleResult();
			} catch (Exception e) {
			}

			Organization sellorg = queryOrganizationByCode(sellreq.getPublicrequest().getAskorgcode());
			
			// 由中心统一生成电子票号,取票密码
			List<SellticketIn> tickets = sellreq.getTickets();
			for (SellticketIn ti : tickets) {
				// ti.setTicketno(RandomTicketNo.random());取网站传过来的电子票号
				String TI_SQL = "SELECT t FROM Ticketsell t WHERE t.netticketid=:netticketid";
				Query queryti = JPA.em().createQuery(TI_SQL);
				queryti.setParameter("netticketid", ti.getNetticketid());
				Ticketsell ts = null;
				try {
					ts = (Ticketsell) queryti.getSingleResult();
				} catch (Exception e) {
				}
				if (ts != null) {
					LogUtil.logerror("售票记录已经存在，但又在消费售票消息" + jsonString);
					return true;
				}
			}

			if (!JPA.em().getTransaction().isActive()) {
				JPA.em().getTransaction().begin();
			}
			try {
				List<Sellticketout> remotetickets = sellres.getTickets();
				String seattype = sellreq.getSeattype();
				Map<String,String> vercodes = new HashMap<String,String>();
				for(Sellticketout st : remotetickets){
					vercodes.put(st.getNetticketid(), st.getVerificationcode());
				}
				// 售票成功
//				int saleseats = 0;
//				int takekids = 0;
				String equipmentproviders = sellreq.getEquipmentproviders();
				String seller = (sellreq.getSeller() == null || "".equals(sellreq.getSeller().trim()))?sellorg.name:sellreq.getSeller();
				String accountorgcode = (sellreq.getAccountorgcode() == null || "".equals(sellreq.getAccountorgcode().trim()))?sellorg.code:sellreq.getAccountorgcode();
				String canreturnmoneyback = (sellreq.getCanreturnmoneyback() == null || "".equals(sellreq.getCanreturnmoneyback().trim()))?"0":sellreq.getCanreturnmoneyback();
				String ticketoutlets = (sellreq.getTicketoutlets() == null || "".equals(sellreq.getTicketoutlets().trim()))?sellorg.name:sellreq.getTicketoutlets();
				String sellway = (sellreq.getSellway() == null || "".equals(sellreq.getSellway().trim()))?"0":sellreq.getSellway();
				String paymethod = (sellreq.getPaymethod() == null || "".equals(sellreq.getPaymethod().trim()))?"3":sellreq.getPaymethod();
				for (SellticketIn ti : tickets) {
					Ticketsell ts = new Ticketsell();

					ts.id = CommonUtils.GetPKID(TableIndex.ticketsell);
					ts.buspark = (sp==null?null:sp.busbrand);
					ts.certificateno = ti.getCertificateno();
					ts.certificatetype = ti.getCertificatetype();
					ts.createby = 0;
					ts.createtime = new Date();
					ts.customername = ti.getCustomername();
					ts.departdate = departdate;
					ts.departorgcode = departorg.code;
					ts.departtime = sellreq.getDeparttime();
					ts.discountrate = 1;// 先默认为1，不打折
					ts.distance = (sp==null?0:sp.rundistance);
					ts.eticketno = ti.getTicketno();
					ts.fullprice = ti.getPrice();
					ts.islineschedule = (sp==null?false:sp.islinework);
					// if (ts.getEticketno().equals("1")) {
					if (sellreq.getEticket().equals("1")) {
						ts.takestatus = "1";// 0：无需取票 1：未取票 2：已取票
						//ts.sellway = "0";// 网上售票
					} else {
						ts.takestatus = "0";// 0：无需取票 1：未取票 2：已取票
						//ts.sellway = "2";// 售票
					}
					ts.sellway = sellway;
//					if (ti.getTakekid().equals("1")) {
//						takekids++;
//					}
					ts.istakekid = ti.getTakekid().equals("1") ? true : false;

					ts.orderno = sellreq.getOrderno();
					ts.paymethod = paymethod;// 银联卡
					ts.phone = ti.getPhone();
					ts.price = ti.getPrice();
					ts.reachstationcode = reachstationcode;
					ts.schedulecode = sellreq.getSchedulecode();
					ts.schedulepriceid = (sp==null?null:sp.id);
					String netticketid = ti.getNetticketid();
					String seatno = ti.getSeatno();
					boolean isfind = false;
					// 最后座位号以车站返回为准
					for (Sellticketout tout : remotetickets) {
						if (netticketid.equals(tout.getNetticketid())) {
							seatno = tout.getSeatno();
							isfind = true;
//							saleseats++;
						}
					}
					if (!isfind) {
						LogUtil.logerror("售票消费失败，请求消息与返回消息不一致" + jsonString);
						if (!JPA.em().getTransaction().isActive()) {//开启事务
							JPA.em().getTransaction().begin();
						}
						JPA.em().getTransaction().rollback();
						ErrorMailUtil.sendMail("BSELL0001", "售票消费失败，请求消息与返回消息不一致" + jsonString);
						return false;
					}
					ts.netticketid = netticketid;
					ts.seatno = seatno;

					ts.seattype = seattype;
					ts.sellby = 0;
					ts.sellip = getServersaddressIp(sellorg.serversaddress);
					ts.sellorgcode = sellorg.code;
					Date stime = null;
					try{
						stime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(sellres.getPublicresponse().getReturntime());
					}catch(Exception e){
						stime = new SimpleDateFormat("yyyyMMddHHmmss").parse(sellres.getPublicresponse().getReturntime());
					}
					ts.selltime = stime;

					ts.servicefee = new BigDecimal(0);// 暂时t存为0
					ts.ticketentrance = (sp==null?null:sp.ticketentrance);
					ts.ticketno = ti.getTicketno();
					ts.ticketoutlets = ticketoutlets;
					ts.equipmentproviders = equipmentproviders;
					ts.seller = seller;
					ts.accountorgcode = accountorgcode;
					ts.canreturnmoneyback = canreturnmoneyback;
					ts.ticketstatus = "0";
					ts.tickettype = ti.getTickettype();
					ts.toplimitprice = (sp==null?null:new BigDecimal(sp.topprice));
					ts.updateby = 0;
					ts.updatetime = ts.selltime;
					ts.verificationcode = vercodes.get(ts.netticketid);
					ts.waitingroom = (sp==null?null:sp.waitingroom);
					ts.startstationname = ti.getStartstationname();
					ts.venue = ti.getVenue();
					ts.ticketprice = ti.getTicketprice();
					if (sp!=null && sp.remainseats != 0) {
						sp.remainseats = sp.remainseats - 1;
					}
					if (sp!=null && ts.istakekid) {
						sp.remainkidseats = sp.remainkidseats - 1;
					}
					if(sp != null){
						sp.updatetime = new Date();
					}
					ts.customerid = 0L;
					ts.save();
					if (ti.getPremium()!=null&&ti.getPremium().compareTo(new BigDecimal(0)) > 0) {
						Insurance insure = new Insurance();
						insure.id = CommonUtils.GetPKID(TableIndex.insurance);
						insure.createby = 0;
						insure.createtime = new Date();
						insure.netticketid = netticketid;
						insure.customerid = 0L;
						insure.customername = ts.customername;
						insure.certificateno = ts.certificateno;
						insure.certificatetype = ts.certificatetype;
						insure.departdate = new SimpleDateFormat("yyyy-MM-dd").parse(sellreq.getDepartdate());
						insure.departtime = sellreq.getDeparttime();
						insure.insurancestatus = "0";
						insure.insuretype = ti.getInsuretype();
						insure.departorgcode = departorg.code;
						insure.reachstationcode = reachstation.code;
						insure.reachstationname = reachstation.name;
						insure.paymethod = "3";
						insure.premium = ti.getPremium();
						insure.reachstationcode = reachstationcode;
						insure.schedulecode = sellreq.getSchedulecode();
						insure.seatno = ti.getSeatno();
						insure.sellby = 0;
						insure.sellip = getServersaddressIp(sellorg.serversaddress);
						insure.selltime = new Date();
						insure.ticketoutlets = sellorg.name;
						insure.updateby = 0;
						insure.updatetime = new Date();
						insure.ticketno = ts.ticketno;
						insure.sellorgcode = sellorg.code;
						insure.insureamount = ti.getInsureamount();
						insure.save();
					}
				}
				String orderno = sellreq.getOrderno();
				String ORDER_SQL = "select t from Order t where t.orderno='" + orderno + "'";
				Query queryorder = JPA.em().createQuery(ORDER_SQL);
				Order order = null;
				try {
					order = (Order) queryorder.getSingleResult();
				} catch (Exception e) {
					LogUtil.logerror("未找到订单号为" + orderno + "的订单信息");
					if (!JPA.em().getTransaction().isActive()) {//开启事务
						JPA.em().getTransaction().begin();
					}
					JPA.em().getTransaction().rollback();
					ErrorMailUtil.sendMail("BSELL0001", e);
					return false;
				}
				// if (order == null) {
				// order = new Order();
				// order.createby = 0;
				// order.createtime = new Date();
				// order.departdate = departdate;
				// order.departorgcode = departorg.code;
				// order.departtime = sellreq.getDeparttime();
				// order.lockdelay = 10;
				// order.locktime = new Date();
				// order.orderno = sellreq.getOrderno();
				// order.reachstationcode = sellreq.getReachstationcode();
				// order.schedulecode = sellreq.getSchedulecode();
				// order.seatnum = sellreq.getSeatnum();
				// order.seattype = sellreq.getSeattype();
				// order.sellorgcode = sellorg.code;
				// order.sellway = "7";// 网上售票
				// order.updateby = 0;
				// order.status = "0";// 新建立
				// order.updatetime = new Date();
				// }
				order.status = "1";
				order.updatetime = new Date();
				order.startstationname = tickets.get(0).getStartstationname();
				order.venue = tickets.get(0).getVenue();
				order.ticketprice = tickets.get(0).getTicketprice();
				order.save();
				// sp.setRemainseats(sp.getRemainseats() - saleseats);
				// sp.setRemainkidseats(sp.getRemainkidseats() - takekids);
				// sp.setUpdatetime(new Date());
				// dao.merge(sp);
				if (!JPA.em().getTransaction().isActive()) {
					JPA.em().getTransaction().begin();
				}
				JPA.em().getTransaction().commit();
				finishMsg(jsonString ,new Date());
				return true;
			} catch (Exception e) {
				LogUtil.logerror("售票失败：未知异常" + jsonString, e);
				if (!JPA.em().getTransaction().isActive()) {//开启事务
					JPA.em().getTransaction().begin();
				}
				JPA.em().getTransaction().rollback();
				ErrorMailUtil.sendMail("BSELL0001", e);
				return false;
			}
		} catch (Exception e) {
			if (!JPA.em().getTransaction().isActive()) {//开启事务
				JPA.em().getTransaction().begin();
			}
			JPA.em().getTransaction().rollback();
			LogUtil.logerror("售票失败：未知异常" + jsonString, e);
			ErrorMailUtil.sendMail("BSELL0001", e);
			return false;
		}
	}

	public boolean sellunknown(String jsonString) {
//		SellSuccessVo sellsuccessvo = null;
		SellUnknownVo unknownvo = null;
		Sellrequest sellreq = null;
		CenterSellRequest centersellreq = null;
		// sellres.setPublicresponse(PublicXmlUtil.newPublicresponse());
		if(JPA.em().getTransaction().isActive()){
			JPA.em().getTransaction().commit();
		}
//		try {
//			sellsuccessvo = (SellSuccessVo) JsonUtil.readJson2Entity(jsonString, SellSuccessVo.class);
//		} catch (Exception e) {
//			LogUtil.logerror("网站请求格式错误,XML转换失败" + jsonString);
//			// sellres.getPublicresponse().setResultcode("NASELL1000");
//			// sellres.getPublicresponse().setResultmsg("网站请求格式错误");
//			ErrorMailUtil.sendMail("BSEUN0001", e);
//			return false;
//		}
		try {
			unknownvo = (SellUnknownVo) JsonUtil.readJson2Entity(jsonString, SellUnknownVo.class);
		} catch (Exception e) {
			LogUtil.logerror("网站请求格式错误,XML转换失败" + jsonString);
			// sellres.getPublicresponse().setResultcode("NASELL1000");
			// sellres.getPublicresponse().setResultmsg("网站请求格式错误");
			ErrorMailUtil.sendMail("BSEUN0001", e);
			return false;
		}
		centersellreq = unknownvo.getRequestcontent();
		sellreq = changeParam(centersellreq);
		StringBuilder sb = new StringBuilder();
		for(SellticketIn si : sellreq.getTickets()){
			sb.append("'").append(si.getNetticketid()).append("',");
		}
		String netticketids = sb.toString().substring(0, sb.toString().length()-1);
		String SQL = "SELECT * FROM ticketsell  WHERE netticketid in ("+netticketids+")";
		List<Ticketsell> ticketsells = JPA.em().createNativeQuery(SQL, Ticketsell.class).getResultList();
		if(ticketsells.size()>0 && ticketsells.size() == sellreq.getTickets().size()){
			return true;
		}
		Organization departorg = queryOrganizationByCode(sellreq.getPublicrequest().getTargetorgcode());

		String sql = "select o from Station o where o.code='" + sellreq.getReachstationcode() + "' and o.orgcode='" + departorg.code + "'";
		Query queryst = JPA.em().createQuery(sql);
		Station reachstation = null;
		try {
			reachstation = (Station) queryst.getSingleResult();
		} catch (Exception e) {
			// 不存在该到站的编码
			LogUtil.logerror("不存在orgcode=" + departorg.code + "code=" + sellreq.getReachstationcode() + "到站编码");
			ErrorMailUtil.sendMail("BSEUN0001", "不存在orgcode=" + departorg.code + "code=" + sellreq.getReachstationcode() + "到站编码");
			return false;
		}

		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Date departdate;
		try {
			departdate = sdf.parse(sellreq.getDepartdate());
		} catch (ParseException e1) {
			LogUtil.logerror("发车日期格式转换失败");
			ErrorMailUtil.sendMail("BSEUN0001", e1);
			return false;
		}

		String reachstationcode = sellreq.getReachstationcode();
		String SPLIST_SQL = "select s from Scheduleprice s where s.departdate=:departdate and s.orgcode=:orgcode and s.schedulecode=:schedulecode and s.reachstationcode=:reachstationcode and s.seattype=:seattype";
		Query querysp = JPA.em().createQuery(SPLIST_SQL);
		querysp.setParameter("departdate", departdate);
		querysp.setParameter("orgcode", departorg.code);
		querysp.setParameter("schedulecode", sellreq.getSchedulecode());
		querysp.setParameter("reachstationcode", reachstationcode);
		querysp.setParameter("seattype", sellreq.getSeattype());
		Scheduleprice sp = null;
		try {
			sp = (Scheduleprice) querysp.getSingleResult();
		} catch (Exception e) {
		}

		Organization sellorg = queryOrganizationByCode(sellreq.getPublicrequest().getAskorgcode());

		List<SellticketIn> tickets = sellreq.getTickets();
		for (SellticketIn ti : tickets) {
			// ti.setTicketno(RandomTicketNo.random());取网站传过来的电子票号
			ti.setVerificationcode(RandomTicketNo.random(10));
		}

		Orderqueryresponse orderqueryres = getOrderResponse(sellreq.getOrderno(), sellreq.getPublicrequest(), null);
		if (orderqueryres == null) {
			LogUtil.logerror("售票第三态订单查询调用失败");
			ErrorMailUtil.sendMail("BSEUN0001", "售票第三态订单查询调用失败");
			return false;
		}

		if ("0000".equals(orderqueryres.getPublicresponse().getResultcode())) {
			List<Orderticket> ordertickets = orderqueryres.getTickets();
			try {
				if (! JPA.em().getTransaction().isActive()) {
					JPA.em().getTransaction().begin();
				}
				String seattype = sellreq.getSeattype();
				// 售票成功
				int saleseats = 0;
				int takekids = 0;
				String equipmentproviders = sellreq.getEquipmentproviders();
				String seller = (sellreq.getSeller() == null || "".equals(sellreq.getSeller().trim()))?sellorg.name:sellreq.getSeller();
				String accountorgcode = (sellreq.getAccountorgcode() == null || "".equals(sellreq.getAccountorgcode().trim()))?sellorg.code:sellreq.getAccountorgcode();
				String canreturnmoneyback = (sellreq.getCanreturnmoneyback() == null || "".equals(sellreq.getCanreturnmoneyback().trim()))?"0":sellreq.getCanreturnmoneyback();
				String ticketoutlets = (sellreq.getTicketoutlets() == null || "".equals(sellreq.getTicketoutlets().trim()))?sellorg.name:sellreq.getTicketoutlets();
				String sellway = (sellreq.getSellway() == null || "".equals(sellreq.getSellway().trim()))?"0":sellreq.getSellway();
				String paymethod = (sellreq.getPaymethod() == null || "".equals(sellreq.getPaymethod().trim()))?"3":sellreq.getPaymethod();
				for (int i = 0; i < ordertickets.size(); i++) {
					Orderticket ticket = ordertickets.get(i);
					SellticketIn ti = tickets.get(i);
					String TI_SQL = "SELECT t FROM Ticketsell t WHERE t.netticketid=:netticketid";
					Query queryti = JPA.em().createQuery(TI_SQL);
					queryti.setParameter("netticketid", ti.getNetticketid());
					Ticketsell ts = null;
					try {
						ts = (Ticketsell) queryti.getSingleResult();
					} catch (Exception e) {
					}
					if (ts == null) {
						ts = new Ticketsell();
						ts.id = CommonUtils.GetPKID(TableIndex.ticketsell);
						ts.buspark = (sp==null?null:sp.busbrand);
						ts.certificateno = ti.getCertificateno();
						ts.certificatetype = ti.getCertificatetype();
						ts.createby = 0;
						ts.createtime = new Date();
						ts.customername = ti.getCustomername();
						ts.departdate = departdate;
						ts.departorgcode = departorg.code;
						ts.departtime = sellreq.getDeparttime();
						ts.discountrate = 1;// 先默认为1，不打折
						ts.distance = (sp==null?null:sp.rundistance);
						ts.ticketno = ti.getTicketno();
						ts.fullprice = ti.getPrice();
						ts.islineschedule = (sp==null?null:sp.islinework);
						// if (ts.getEticketno().equals("1")) {
						if (sellreq.getEticket().equals("1")) {
							ts.takestatus = "1";// 0：无需取票 1：未取票 2：已取票
							//ts.sellway = "0";// 网上售票
						} else {
							ts.takestatus = "0";// 0：无需取票 1：未取票 2：已取票
							//ts.sellway = "2";// 售票
						}
						ts.sellway = sellway;
						if (ti.getTakekid().equals("1")) {
							takekids++;
						}
						ts.istakekid = ti.getTakekid().equals("1") ? true : false;

						ts.orderno = sellreq.getOrderno();
						ts.paymethod = paymethod;// 银联卡
						ts.phone = ti.getPhone();
						ts.price = ti.getPrice();
						ts.reachstationcode = reachstationcode;
						ts.schedulecode = sellreq.getSchedulecode();
						ts.schedulepriceid = (sp==null?null:sp.id);
						String netticketid = ti.getNetticketid();
						ts.netticketid = netticketid;
						ts.seatno = ticket.getSeatno();
						saleseats++;

						ts.seattype = seattype;
						ts.sellby = 0;
						ts.sellip = getServersaddressIp(sellorg.serversaddress);
						ts.sellorgcode = sellorg.code;
						ts.selltime =  new SimpleDateFormat("yyyyMMddHHmmss").parse(ticket.getSelltime());

						ts.servicefee = new BigDecimal(0);// 暂时t存为0
						ts.ticketentrance = (sp==null?null:sp.ticketentrance);
						ts.ticketno = ti.getTicketno();
						ts.ticketoutlets = ticketoutlets;
						ts.equipmentproviders = equipmentproviders;
						ts.seller = seller;
						ts.accountorgcode = accountorgcode;
						ts.canreturnmoneyback = canreturnmoneyback;
						ts.ticketstatus = "0";
						ts.tickettype = ti.getTickettype();
						ts.toplimitprice = (sp==null?null:new BigDecimal(sp.topprice));
						ts.updateby = 0;
						ts.updatetime = ts.selltime;
						ts.startstationname = ti.getStartstationname();
						ts.venue = ti.getVenue();
						ts.ticketprice = ti.getTicketprice();
						if(ticket.getVerificationcode() == null || ticket.getVerificationcode().trim().length()<=0){
							ts.verificationcode = ti.getVerificationcode();
						}else{
							ts.verificationcode = ticket.getVerificationcode();
						}
						ts.waitingroom = (sp==null?null:sp.waitingroom);
						if (sp != null && sp.remainseats != 0) {
							sp.remainseats = sp.remainseats - 1;
						}
						if (sp != null && ts.istakekid) {
							sp.remainkidseats = sp.remainkidseats - 1;
						}
						if(sp != null){
							sp.updatetime = new Date();
						}

						ts.customerid = 0L;
						ts.save();
						if (ti.getPremium().compareTo(new BigDecimal(0)) > 0) {
							Insurance insure = new Insurance();
							insure.id = CommonUtils.GetPKID(TableIndex.insurance);
							insure.createby = 0;
							insure.createtime = new Date();
							insure.netticketid = netticketid;
							insure.customerid = 0L;
							insure.customername = ts.customername;
							insure.certificateno = ts.certificateno;
							insure.certificatetype = ts.certificatetype;
							insure.departdate = new SimpleDateFormat("yyyy-MM-dd").parse(sellreq.getDepartdate());
							insure.departtime = sellreq.getDeparttime();
							insure.insurancestatus = "0";
							insure.insuretype = ti.getInsuretype();
							insure.departorgcode = departorg.code;
							insure.reachstationcode = reachstation.code;
							insure.reachstationname = reachstation.name;
							insure.paymethod = "3";
							insure.premium = ti.getPremium();
							insure.reachstationcode = reachstationcode;
							insure.schedulecode = sellreq.getSchedulecode();
							insure.seatno = ti.getSeatno();
							insure.sellby = 0;
							insure.sellip = getServersaddressIp(sellorg.serversaddress);
							insure.selltime = new Date();
							insure.ticketoutlets = sellorg.name;
							insure.updateby = 0;
							insure.updatetime = new Date();
							insure.ticketno = ts.ticketno;
							insure.sellorgcode = sellorg.code;
							insure.insureamount = ti.getInsureamount();
							insure.save();
						}
						String orderno = sellreq.getOrderno();
						String ORDER_SQL = "select t from Order t where t.orderno='" + orderno + "'";
						Query queryorder = JPA.em().createQuery(ORDER_SQL);
						Order order = null;
						try {
							order = (Order) queryorder.getSingleResult();
						} catch (Exception e) {
							LogUtil.logerror("未找到订单号为" + orderno + "的订单信息");
							if (!JPA.em().getTransaction().isActive()) {//开启事务
								JPA.em().getTransaction().begin();
							}
							JPA.em().getTransaction().rollback();
							ErrorMailUtil.sendMail("BSEUN0001", "未找到订单号为" + orderno + "的订单信息");
							return false;
						}
						order.status = "1";
						order.updatetime = new Date();
						order.startstationname = tickets.get(0).getStartstationname();
						order.venue = tickets.get(0).getVenue();
						order.ticketprice = tickets.get(0).getTicketprice();
						order.save();
						if(sp != null){
							sp.remainseats = sp.remainseats - saleseats;
							sp.remainkidseats = sp.remainkidseats - takekids;
							sp.updatetime = new Date();
							sp.save();	
						}
					} else {
						LogUtil.logerror("售票消费失败，售票记录已存在" + jsonString);
						if (!JPA.em().getTransaction().isActive()) {//开启事务
							JPA.em().getTransaction().begin();
						}
						JPA.em().getTransaction().rollback();
						return true;
					}
				}
				
				// sp.setRemainseats(sp.getRemainseats() - saleseats);
				// sp.setRemainkidseats(sp.getRemainkidseats() - takekids);
				// sp.setUpdatetime(new Date());
				// dao.merge(sp);
				JPA.em().getTransaction().commit();
				finishMsg(jsonString ,new Date());
				return true;
			} catch (Exception e) {
				LogUtil.logerror("售票失败：未知异常" + jsonString, e);
				if (!JPA.em().getTransaction().isActive()) {//开启事务
					JPA.em().getTransaction().begin();
				}
				JPA.em().getTransaction().rollback();
				ErrorMailUtil.sendMail("BSEUN0001", e);
				return false;
			}
		} else if ("SDTKQR0001".equals(orderqueryres.getPublicresponse().getResultcode())) {
			//售票时产生第三态，后期消费时调用 订单查询 返回售票失败
			return true;
		} else {
			ErrorMailUtil.sendMail("BSEUN0001", orderqueryres.getPublicresponse());
			return false;//订单查询其它异常
		}
	}

//	public static void main(String[] args) {
//		SellUnknownVo unknownvo = (SellUnknownVo) JsonUtil.readJson2Entity("{\"requestcontent\":{\"publicrequest\":{\"askorgcode\":\"HBDLKYLWZX\",\"askorgname\":\"湖北省道路客运联网中心官网\",\"targetorgcode\":\"420503YCZX\",\"asktime\":\"20151113221725\",\"version\":\"1.0.0\",\"signmsg\":\"c02045936088ab16fe2fa7fdadbfc695\"},\"departdate\":\"2015-11-15\",\"schedulecode\":\"903\",\"orderno\":\"94131154537\",\"departtime\":\"12:40\",\"reachstationcode\":\"420607035\",\"seatnum\":1,\"seattype\":\"普通座\",\"eticket\":\"1\",\"ordercustomername\":\"谢永超\",\"ordersex\":\"\",\"ordercertificatetype\":\"0\",\"ordercertificateno\":\"420626199109043510\",\"orderphone\":\"13428982628\",\"orderemail\":\"371002105@qq.com\",\"exchangefee\":0.2,\"isopenapiask\":null,\"sellway\":null,\"paymethod\":null,\"canreturnmoneyback\":\"1\",\"equipmentproviders\":null,\"ticketoutlets\":null,\"seller\":null,\"accountorgcode\":null,\"instation\":null,\"tickets\":[{\"netticketid\":\"ea4effc8-fff8-499d-bfb3-e986d8b08167\",\"takekid\":\"0\",\"seatno\":\"1\",\"price\":65.0,\"tickettype\":\"Q\",\"customername\":\"郭利华\",\"sex\":\"\",\"certificatetype\":\"0\",\"certificateno\":\"422802199303013923\",\"phone\":\"13510690616\",\"insuretype\":\"\",\"premium\":0.0,\"insureamount\":0.0,\"ticketno\":\"20151113221725898\",\"verificationcode\":\"65212012641\",\"startstationname\":null,\"venue\":null,\"ticketprice\":null}]}}", SellUnknownVo.class);
//	}
	public boolean returnticket(String jsonString) {
		Date date = new Date();
		ReturnTicketSuccessVo returnticketsuccessvo = null;
		Returnrequest request = null;
		Returnresponse response = null;
		try {
			returnticketsuccessvo = (ReturnTicketSuccessVo) JsonUtil.readJson2Entity(jsonString, ReturnTicketSuccessVo.class);
		} catch (Exception e) {
			LogUtil.logerror("网站请求格式错误,XML转换失败" + jsonString, e);
			ErrorMailUtil.sendMail("BRTTI0001", e);
			return false;
		}
		if(JPA.em().getTransaction().isActive()){
			JPA.em().getTransaction().commit();
		}
		request = returnticketsuccessvo.getRequestcontent();
		response = returnticketsuccessvo.getResponsecontent();
		
		String orderno = request.getOrderno();
		String netticketid = request.getNetticketid();
		Ticketsell ticketsell = null;
		try {
			ticketsell = (Ticketsell) JPA.em().createQuery("select t from Ticketsell t where t.orderno = :orderno and t.netticketid = :netticketid").setParameter("netticketid", netticketid).setParameter("orderno", orderno).getSingleResult();
		} catch (NoResultException e1) {
			ticketsell = null;
		} catch (Exception e1){
			LogUtil.logerror("未找到订单号为" + orderno + "电子票号为" + netticketid + "车票信息",e1);
		}
		if(ticketsell==null){
			LogUtil.logerror("未找到订单号为" + orderno + "电子票号为" + netticketid + "车票信息");
			ErrorMailUtil.sendMail("BRTTI0001", "未找到订单号为" + orderno + "电子票号为" + netticketid + "车票信息");
			return false;
		}
		Ticketreturn tr = null;
		try{
			tr = (Ticketreturn) JPA.em().createQuery("select t from Ticketreturn t where t.id = :id").setParameter("id", ticketsell.id).getSingleResult();
		}catch(Exception e){
		}
		if(tr != null){
			return true;
		}
		String eticketno = ticketsell.eticketno;
		boolean returnway = true;
		if(eticketno==null||"".equals(eticketno)){
			returnway = false;
		}
		Organization sellorg = queryOrganizationByCode(request.getPublicrequest().getAskorgcode());

		try {
//			Date departdate = ticketsell.departdate;
//			String departtime = ticketsell.departtime;
//			Date datetime = DateUtils.mergerDateAndTime(departdate, departtime);
			Double returnFee=request.getReturnfee();
//			if(returnFee == 0.00d){
//				Double returnRate = getReturnRate(datetime);
//				if(returnRate==1.00d){
//					LogUtil.logerror("退票时间" + datetime + "超过限定时间" + returnRate + "网站无法退票");
//					return false;
//				}
//			    returnFee = getReturnFee(ticketsell.price.doubleValue(), datetime);
//			    response.setReturnfee(returnFee);
//				//ticketsell.returnrate = new BigDecimal(returnRate);
//			}else{
//				DecimalFormat  df  =  new  DecimalFormat(".00");
//				try {
//					returnFee = df.parse(df.format(returnFee)).doubleValue();
//				} catch (ParseException e) {
//					LogUtil.logerror("退票手续费类型转换失败", e);
//					return false;
//				}
//			 BigDecimal price=new BigDecimal(returnFee);
//			 BigDecimal returnfe = price.divide(ticketsell.price,2, BigDecimal.ROUND_HALF_EVEN);
//			// ticketsell.returnrate = returnfe;
//			}
//			BigDecimal returnfe = new BigDecimal(Double.toString(returnFee)).divide(ticketsell.price,2, BigDecimal.ROUND_HALF_EVEN);
			Date rtime;
			try{
				rtime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(response.getPublicresponse().getReturntime());
			}catch(Exception e){
				rtime = new SimpleDateFormat("yyyyMMddHHmmss").parse(response.getPublicresponse().getReturntime());
			}
			if(!JPA.em().getTransaction().isActive()){
				JPA.em().getTransaction().begin();
			}
			ticketsell.ticketstatus =  "1";
			//ticketsell.returnfee = new BigDecimal(returnFee);
			//ticketsell.returntime = date;
			ticketsell.updateby = 0;
			ticketsell.updatetime = rtime;
			ticketsell.save();
			
			Ticketreturn ticketreturn = Ticketreturn.find("id=?", ticketsell.id).first();
			if(ticketreturn==null){
				ticketreturn = new Ticketreturn();
			}else{
				return true;
			}
			ticketreturn.id = ticketsell.id;
			ticketreturn.netticketid = ticketsell.netticketid;
			ticketreturn.departorgcode = ticketsell.departorgcode;
			ticketreturn.departdate = ticketsell.departdate;
			ticketreturn.returnorgcode = sellorg.code;
			ticketreturn.ticketno = ticketsell.ticketno;
			ticketreturn.ticketprice = ticketsell.price;
			ticketreturn.charges = returnFee;
			ticketreturn.returnamount = ticketsell.price.doubleValue()-returnFee;
			ticketreturn.returnvoucherno = request.getReturnvoucherno();
			ticketreturn.returnname = request.getPublicrequest().getAskorgname();
			
			ticketreturn.returntime = rtime;
			ticketreturn.returnip = getServersaddressIp(sellorg.serversaddress);
			ticketreturn.ticketoutlets = ticketsell.ticketoutlets;
			ticketreturn.returnfeemode=response.getReturnfeemode();
			if(returnway){
				ticketreturn.returnway = "0";//电子票   网站退票
			}else{
				ticketreturn.returnway = "1";//非电子票  车站退票
			}
			ticketreturn.turnoverdetailid = 0;
			ticketreturn.createtime = date;
			ticketreturn.createby = 0;
			ticketreturn.updatetime = date;
			ticketreturn.updateby = 0;
			
			JPA.em().persist(ticketreturn);
			Insurance insurance = null;
			try {
				insurance=(Insurance)JPA.em().createQuery("select i from Insurance i where i.netticketid = :netticketid").setParameter("netticketid", ticketsell.netticketid).getSingleResult();
			} catch (Exception e) {
			}
			if(insurance !=null){
				insurance.updatetime = date;
				insurance.insurancestatus = "1";
				//更新保险状态
				insurance.save();
				//插入保险退票信息
				InsuranceReturn insuranceReturn = new InsuranceReturn();
				insuranceReturn.id = insurance.id;
				insuranceReturn.insuranceid = insurance.id;
				insuranceReturn.netticketid = ticketsell.netticketid;
				insuranceReturn.departorgcode = ticketsell.departorgcode;
				insuranceReturn.departdate = ticketsell.departdate;
				insuranceReturn.returnorgcode = sellorg.code;
				insuranceReturn.premium = insurance.premium;
				insuranceReturn.returnname = request.getPublicrequest().getAskorgname();
				insuranceReturn.returntime = date;
				insuranceReturn.returnway = ticketreturn.returnway;
				insuranceReturn.returnip = getServersaddressIp(sellorg.serversaddress);
				insuranceReturn.ticketoutlets = ticketsell.ticketoutlets;
				insuranceReturn.createtime = date;
				insuranceReturn.createby = 0;
				insuranceReturn.updatetime = date;
				insuranceReturn.updateby = 0;
			
				JPA.em().persist(insuranceReturn);
			}
			JPA.em().getTransaction().commit();
			finishMsg(jsonString ,new Date());
			return true;
		} catch (Exception e) {
			LogUtil.logerror("退票消费失败" + jsonString, e);
			if (!JPA.em().getTransaction().isActive()) {//开启事务
				JPA.em().getTransaction().begin();
			}
			JPA.em().getTransaction().rollback();
			ErrorMailUtil.sendMail("BRTTI0001", e);
			return false;
		}	
	}
	
	public boolean cancelticket(String jsonString) {
		Date date = new Date();
		CancelTicketVo cancelvo = null;
		Cancelrequest request = null;
		Cancelresponse response = null;
		try {
			cancelvo = (CancelTicketVo) JsonUtil.readJson2Entity(jsonString, CancelTicketVo.class);
		} catch (Exception e) {
			LogUtil.logerror("网站请求格式错误,XML转换失败" + jsonString, e);
			ErrorMailUtil.sendMail("BCACL0001", e);
			return false;
		}
		if(JPA.em().getTransaction().isActive()){
			JPA.em().getTransaction().commit();
		}
		request = cancelvo.getRequestcontent();
		response = cancelvo.getResponsecontent();
		
		String orderno = request.getOrderno();
		String netticketid = request.getNetticketid();
		Ticketsell ticketsell = null;
		try{
			ticketsell = (Ticketsell) JPA.em().createQuery("select t from Ticketsell t where t.orderno = :orderno and t.netticketid = :netticketid")
					.setParameter("orderno", orderno).setParameter("netticketid", netticketid).getSingleResult();
		}catch(Exception e){
			LogUtil.logerror("未找到订单号为" + orderno + "电子票号为" + netticketid + "车票信息",e);
			ErrorMailUtil.sendMail("BCACL0001", "未找到订单号为" + orderno + "电子票号为" + netticketid + "车票信息");
			return false;
		}
		if(ticketsell==null){
			LogUtil.logerror("未找到订单号为" + orderno + "电子票号为" + netticketid + "车票信息");
			ErrorMailUtil.sendMail("BCACL0001", "未找到订单号为" + orderno + "电子票号为" + netticketid + "车票信息");
			return false;
		}
		Organization cancelorg = queryOrganizationByCode(request.getPublicrequest().getAskorgcode());

		try {
			Date rtime;
			try{
				rtime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(response.getPublicresponse().getReturntime());
			}catch(Exception e){
				rtime = new SimpleDateFormat("yyyyMMddHHmmss").parse(response.getPublicresponse().getReturntime());
			}
			if(!JPA.em().getTransaction().isActive()){
				JPA.em().getTransaction().begin();
			}
			ticketsell.ticketstatus =  "2";
			//ticketsell.returnfee = new BigDecimal(returnFee);
			//ticketsell.returntime = date;
			ticketsell.updateby = 0;
			ticketsell.updatetime = rtime;
			ticketsell.save();
			
			TicketCancel ticketcancel = TicketCancel.find("id=?", ticketsell.id).first();
			if(ticketcancel == null){
				ticketcancel = new TicketCancel();
			}else{
				return true;
			}
			ticketcancel.id = ticketsell.id;
			ticketcancel.netticketid = ticketsell.netticketid;
			ticketcancel.departorgcode = ticketsell.departorgcode;
			ticketcancel.departdate = ticketsell.departdate;
			ticketcancel.cancelorgcode = cancelorg.code;
			ticketcancel.ticketno = ticketsell.ticketno;
			ticketcancel.ticketprice = ticketsell.price;
			ticketcancel.cancelname = request.getPublicrequest().getAskorgname();
			ticketcancel.canceltime = rtime;
			ticketcancel.cancelip = getServersaddressIp(cancelorg.serversaddress);
			ticketcancel.cancelticketoutlets = ticketsell.ticketoutlets;
			ticketcancel.cancelmode="0";
			ticketcancel.turnoverdetailid = 0;
			ticketcancel.createtime = date;
			ticketcancel.createby = 0;
			ticketcancel.updatetime = rtime;
			ticketcancel.updateby = 0;
			
			JPA.em().persist(ticketcancel);
			
			JPA.em().getTransaction().commit();
			finishMsg(jsonString ,new Date());
			return true;
		} catch (Exception e) {
			LogUtil.logerror("废票消费失败" + jsonString, e);
			if (!JPA.em().getTransaction().isActive()) {//开启事务
				JPA.em().getTransaction().begin();
			}
			JPA.em().getTransaction().rollback();
			ErrorMailUtil.sendMail("BCACL0001", e);
			return false;
		}	
	}
	
	public boolean changeticketno(String jsonString){
		ChangeTicketnoVo changeticketnovo = null;
		Changeticketnorequest request = null;
		if(JPA.em().getTransaction().isActive()){
			JPA.em().getTransaction().commit();
		}
		try {
			changeticketnovo = (ChangeTicketnoVo) JsonUtil.readJson2Entity(jsonString, ChangeTicketnoVo.class);
		} catch (Exception e) {
			LogUtil.logerror("网站请求格式错误,XML转换失败" + jsonString, e);
			ErrorMailUtil.sendMail("BCHTN0001", e);
			return false;
		}
		request = changeticketnovo.getRequestcontent();
		Ticketsell ticketsell = null;
		try{
			ticketsell = (Ticketsell) JPA.em().createQuery("select t from Ticketsell t where t.orderno = :orderno and t.netticketid = :netticketid")
					.setParameter("orderno", request.getOrderno()).setParameter("netticketid", request.getNetticketid()).getSingleResult();
			
		}catch(Exception e){
			LogUtil.logerror("未找到订单号为" + request.getOrderno() + "电子票号为" + request.getNetticketid() + "车票信息",e);
			ErrorMailUtil.sendMail("BCHTN0001", "未找到订单号为" + request.getOrderno() + "电子票号为" + request.getNetticketid() + "车票信息");
			return false;
		}
		if(ticketsell==null){
			LogUtil.logerror("未找到订单号为" + request.getOrderno() + "电子票号为" + request.getNetticketid() + "车票信息");
			ErrorMailUtil.sendMail("BCHTN0001", "未找到订单号为" + request.getOrderno() + "电子票号为" + request.getNetticketid() + "车票信息");
			return false;
		}
		try{
			if(!JPA.em().getTransaction().isActive()){
				JPA.em().getTransaction().begin();
			}
			ticketsell.ticketno = request.getNewticketno();
			ticketsell.save();
			JPA.em().getTransaction().commit();
			finishMsg(jsonString ,new Date());
			return true;
		} catch (Exception e) {
			LogUtil.logerror("换票重打消费失败" + jsonString, e);
			if (!JPA.em().getTransaction().isActive()) {//开启事务
				JPA.em().getTransaction().begin();
			}
			JPA.em().getTransaction().rollback();
			ErrorMailUtil.sendMail("BCHTN0001",e);
			return false;
		}
	}
	
	public boolean returnunknown(String jsonString) {
		Date date = new Date();
		ReturnUnknownSuccessVo returnunknownsuccessvo = null;
		ReturnUnknownrequest request = null;
		try {
			returnunknownsuccessvo = (ReturnUnknownSuccessVo) JsonUtil.readJson2Entity(jsonString, ReturnUnknownSuccessVo.class);
		} catch (Exception e) {
			LogUtil.logerror("网站请求格式错误,XML转换失败" + jsonString, e);
			ErrorMailUtil.sendMail("BRTUN0001", e);
			return false;
		}
		if(JPA.em().getTransaction().isActive()){
			JPA.em().getTransaction().commit();
		}
		request = returnunknownsuccessvo.getRequestcontent();
		
		Orderqueryresponse orderqueryres = null;
		try {
			orderqueryres = getOrderResponse(request.getOrderno(), request.getPublicrequest(), null);
		} catch (Exception e) {
			LogUtil.logerror("退票第三态订单查询异常" + jsonString, e);
			ErrorMailUtil.sendMail("BRTUN0001", e);
			return false;
		}
		if (orderqueryres == null) {
			LogUtil.logerror("退票第三态订单查询调用失败");
			ErrorMailUtil.sendMail("BRTUN0001", "退票第三态订单查询调用失败");
			return false;
		}

		if ("0000".equals(orderqueryres.getPublicresponse().getResultcode())) {
			boolean findticket = false;
			for (Orderticket ticket : orderqueryres.getTickets()) {
				if(request.getNetticketid()!=null 
						&&request.getNetticketid().equals(ticket.getNetticketid())){
					findticket = true;
					if("1".equals(ticket.getTakestatus()))
					{
						//如果车站退票成功
						String orderno = request.getOrderno();
						if(orderno==null||"".equals(orderno)){
							LogUtil.logerror("网站请求格式错误,订单号不能为空" + jsonString);
							ErrorMailUtil.sendMail("BRTUN0001", "网站请求格式错误,订单号不能为空" + jsonString);
							return false;
						}
						String netticketid = request.getNetticketid();
						Ticketsell ticketsell = (Ticketsell) JPA.em().createQuery("select t from Ticketsell t where t.orderno = :orderno and t.netticketid = :netticketid")
												.setParameter("orderno", orderno).setParameter("netticketid", netticketid).getSingleResult();
						if(ticketsell==null){
							LogUtil.logerror("未找到订单号为" + orderno + "电子票号为" + netticketid + "车票信息");
							ErrorMailUtil.sendMail("BRTUN0001", "未找到订单号为" + orderno + "电子票号为" + netticketid + "车票信息");
							return false;
						}
						Ticketreturn ticreturn = null;
						try{
							ticreturn = (Ticketreturn) JPA.em().createQuery("select t from Ticketreturn t where t.id = :id")
									.setParameter("id", ticketsell.id).getSingleResult();
						}catch(Exception e){
						}
						if(ticreturn != null){
							continue;
						}
						String eticketno = ticketsell.eticketno;
						boolean returnway = true;
						if(eticketno==null||"".equals(eticketno)){
							returnway = false;
						}
						Organization sellorg = queryOrganizationByCode(request.getPublicrequest().getAskorgcode());

						try {
							Date departdate = ticketsell.departdate;
							String departtime = ticketsell.departtime;
							Date datetime = DateUtils.mergerDateAndTime(departdate, departtime);
							Double returnFee=request.getReturnfee();
							if(returnFee == 0.00d){
								Double returnRate = getReturnRate(datetime);
								if(returnRate==1.00d){
									LogUtil.logerror("退票时间" + datetime + "超过限定时间" + returnRate + "网站无法退票");
									ErrorMailUtil.sendMail("BRTUN0001", "退票时间" + datetime + "超过限定时间" + returnRate + "网站无法退票");
									return false;
								}
							    returnFee = getReturnFee(ticketsell.price.doubleValue(), datetime);
								//ticketsell.returnrate = new BigDecimal(returnRate);
							}else{
								DecimalFormat  df  =  new  DecimalFormat(".00");
								try {
									returnFee = df.parse(df.format(returnFee)).doubleValue();
								} catch (ParseException e) {
									LogUtil.logerror("退票手续费类型转换失败", e);
									ErrorMailUtil.sendMail("BRTUN0001", e);
									return false;
								}
//							 BigDecimal price=new BigDecimal(returnFee);
//							 BigDecimal returnfe = price.divide(ticketsell.price,2, BigDecimal.ROUND_HALF_EVEN);
							 //ticketsell.returnrate = returnfe;
							}
							Date rtime = null;
							try{
								rtime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(ticket.getReturntime());
							}catch(Exception e){
								try{
									rtime = new SimpleDateFormat("yyyyMMddHHmmss").parse(ticket.getReturntime());
								}catch(Exception e1){
									rtime = new SimpleDateFormat("yyyy-MM-dd").parse(ticket.getReturntime());
									ErrorMailUtil.sendMail("BRTUN0001", "订单查询返回退票时间格式错误为yyyy-MM-dd     orgcode : "+request.getPublicrequest().getTargetorgcode());
								}
							}
							if(!JPA.em().getTransaction().isActive()){
								JPA.em().getTransaction().begin();
							}
							ticketsell.ticketstatus =  "1";
							//ticketsell.returnfee = new BigDecimal(returnFee);
							//ticketsell.returntime = date;
							ticketsell.updateby = 0;
							ticketsell.updatetime = rtime;
							ticketsell.save();
							
							Ticketreturn ticketreturn = new Ticketreturn();
							ticketreturn.id = ticketsell.id;
							ticketreturn.netticketid = ticketsell.netticketid;
							ticketreturn.departorgcode = ticketsell.departorgcode;
							ticketreturn.departdate = ticketsell.departdate;
							ticketreturn.returnorgcode = sellorg.code;
							ticketreturn.ticketno = ticketsell.ticketno;
							ticketreturn.ticketprice = ticketsell.price;
							ticketreturn.charges = returnFee;
							ticketreturn.returnamount = ticketsell.price.doubleValue()-returnFee;
							ticketreturn.returnvoucherno = request.getReturnvoucherno();
							ticketreturn.returnname = request.getPublicrequest().getAskorgname();
							
							ticketreturn.returntime = rtime;
							ticketreturn.returnip = getServersaddressIp(sellorg.serversaddress);
							ticketreturn.ticketoutlets = ticketsell.ticketoutlets;
							if(returnway){
								ticketreturn.returnway = "0";//电子票   网站退票
							}else{
								ticketreturn.returnway = "1";//非电子票  车站退票
							}
							ticketreturn.turnoverdetailid = 0;
							ticketreturn.createtime = date;
							ticketreturn.createby = 0;
							ticketreturn.updatetime = rtime;
							ticketreturn.updateby = 0;
							
							JPA.em().persist(ticketreturn);
							Insurance insurance = null;
							try {
								insurance=(Insurance)JPA.em().createQuery("select i from Insurance i where i.netticketid = :netticketid").setParameter("netticketid", ticketsell.netticketid).getSingleResult();
							} catch (Exception e) {
							}
							if(insurance !=null){
								insurance.updatetime = date;
								insurance.insurancestatus = "1";
								//更新保险状态
								insurance.save();
								//插入保险退票信息
								InsuranceReturn insuranceReturn = new InsuranceReturn();
								insuranceReturn.id = insurance.id;
								insuranceReturn.insuranceid = insurance.id;
								insuranceReturn.netticketid = ticketsell.netticketid;
								insuranceReturn.departorgcode = ticketsell.departorgcode;
								insuranceReturn.departdate = ticketsell.departdate;
								insuranceReturn.returnorgcode = sellorg.code;
								insuranceReturn.premium = insurance.premium;
								insuranceReturn.returnname = request.getPublicrequest().getAskorgname();
								insuranceReturn.returntime = date;
								insuranceReturn.returnway = ticketreturn.returnway;
								insuranceReturn.returnip = getServersaddressIp(sellorg.serversaddress);
								insuranceReturn.ticketoutlets = ticketsell.ticketoutlets;
								insuranceReturn.createtime = date;
								insuranceReturn.createby = 0;
								insuranceReturn.updatetime = date;
								insuranceReturn.updateby = 0;
							
								JPA.em().persist(insuranceReturn);
							}
							JPA.em().getTransaction().commit();
						} catch (Exception e) {
							LogUtil.logerror("第三态退票事务提交失败" + jsonString, e);
							ErrorMailUtil.sendMail("BRTUN0001", e);
							try {
								if (!JPA.em().getTransaction().isActive()) {//开启事务
									JPA.em().getTransaction().begin();
								}
								JPA.em().getTransaction().rollback();
							} catch (Exception e1) {
								LogUtil.logerror("第三态退票事务回滚失败", e1);
								ErrorMailUtil.sendMail("BRTUN0001", e1);
							}
							return false;
						}	
						finishMsg(jsonString ,new Date());
						return true;
					}
				}else{
					Logger.info("车站退票不成功，退票第三态无需消费");
					return true;
				}
			}
			if(!findticket){
				Logger.error("退票第三态,订单查询没有返回该车票的信息");
				ErrorMailUtil.sendMail("BRTUN0001", "退票第三态,订单查询没有返回该车票的信息");
			}
		}
		return false;
	}

	public boolean cancelunknown(String jsonString) {
		Date date = new Date();
		CancelUnknownVo cancelunknownvo = null;
		Cancelrequest request = null;
		try {
			cancelunknownvo = (CancelUnknownVo) JsonUtil.readJson2Entity(jsonString, CancelUnknownVo.class);
		} catch (Exception e) {
			LogUtil.logerror("网站请求格式错误,XML转换失败" + jsonString, e);
			ErrorMailUtil.sendMail("BCAUN0001", e);
			return false;
		}
		if(JPA.em().getTransaction().isActive()){
			JPA.em().getTransaction().commit();
		}
		request = cancelunknownvo.getRequestcontent();
		
		Orderqueryresponse orderqueryres = null;
		try {
			orderqueryres = getOrderResponse(request.getOrderno(), request.getPublicrequest(), null);
		} catch (Exception e) {
			LogUtil.logerror("废票第三态订单查询异常" + jsonString, e);
			ErrorMailUtil.sendMail("BCAUN0001", e);
			return false;
		}
		if (orderqueryres == null) {
			LogUtil.logerror("废票第三态订单查询调用失败");
			ErrorMailUtil.sendMail("BCAUN0001", "废票第三态订单查询调用失败");
			return false;
		}

		if ("0000".equals(orderqueryres.getPublicresponse().getResultcode())) {
			boolean findticket = false;
			for (Orderticket ticket : orderqueryres.getTickets()) {
				if(request.getNetticketid()!=null 
						&&request.getNetticketid().equals(ticket.getNetticketid())){
					findticket = true;
					if("2".equals(ticket.getTicketstatus()))
					{
						//如果车站废票成功
						String orderno = request.getOrderno();
						if(orderno==null||"".equals(orderno)){
							LogUtil.logerror("网站请求格式错误,订单号不能为空" + jsonString);
							ErrorMailUtil.sendMail("BCAUN0001", "网站请求格式错误,订单号不能为空" + jsonString);
							return false;
						}
						String netticketid = request.getNetticketid();
						Ticketsell ticketsell = null;
						try{
							ticketsell = (Ticketsell) JPA.em().createQuery("select t from Ticketsell t where t.orderno = :orderno and t.netticketid = :netticketid")
													.setParameter("orderno", orderno).setParameter("netticketid", netticketid).getSingleResult();
						}catch(Exception e){
							LogUtil.logerror("未找到订单号为" + orderno + "电子票号为" + netticketid + "车票信息",e);
							ErrorMailUtil.sendMail("BCAUN0001", "未找到订单号为" + orderno + "电子票号为" + netticketid + "车票信息");
							return false;
						}
						if(ticketsell==null){
							LogUtil.logerror("未找到订单号为" + orderno + "电子票号为" + netticketid + "车票信息");
							ErrorMailUtil.sendMail("BCAUN0001", "未找到订单号为" + orderno + "电子票号为" + netticketid + "车票信息");
							return false;
						}
						
						Organization cancelorg = queryOrganizationByCode(request.getPublicrequest().getAskorgcode());

						try {
							
							 
							if(!JPA.em().getTransaction().isActive()){
								JPA.em().getTransaction().begin();
							}
							ticketsell.ticketstatus =  "2";
							//ticketsell.returnfee = new BigDecimal(returnFee);
							//ticketsell.returntime = date;
							ticketsell.updateby = 0;
							ticketsell.updatetime = date;
							ticketsell.save();
							
							TicketCancel ticketcancel = new TicketCancel();
							ticketcancel.id = ticketsell.id;
							ticketcancel.netticketid = ticketsell.netticketid;
							ticketcancel.departorgcode = ticketsell.departorgcode;
							ticketcancel.departdate = ticketsell.departdate;
							ticketcancel.cancelorgcode = cancelorg.code;
							ticketcancel.ticketno = ticketsell.ticketno;
							ticketcancel.ticketprice = ticketsell.price;
							ticketcancel.cancelname = request.getPublicrequest().getAskorgname() == null?request.getPublicrequest().getAskorgcode() : request.getPublicrequest().getAskorgname();
							ticketcancel.canceltime = new Date();
							ticketcancel.cancelip = getServersaddressIp(cancelorg.serversaddress);
							ticketcancel.cancelticketoutlets = ticketsell.ticketoutlets;
							ticketcancel.turnoverdetailid = 0;
							ticketcancel.createtime = date;
							ticketcancel.createby = 0;
							ticketcancel.updatetime = date;
							ticketcancel.updateby = 0;
							ticketcancel.cancelmode = "0";
							JPA.em().persist(ticketcancel);
							JPA.em().getTransaction().commit();
						} catch (Exception e) {
							LogUtil.logerror("第三态废票事务提交失败" + jsonString, e);
							ErrorMailUtil.sendMail("BCAUN0001", e);
							try {
								if (!JPA.em().getTransaction().isActive()) {//开启事务
									JPA.em().getTransaction().begin();
								}
								JPA.em().getTransaction().rollback();
							} catch (Exception e1) {
								LogUtil.logerror("第三态废票事务回滚失败", e1);
								ErrorMailUtil.sendMail("BCAUN0001", e1);
							}
							return false;
						}	
						finishMsg(jsonString ,new Date());
						return true;
					}
				}else{
					Logger.info("车站废票不成功，废票第三态无需消费");
					return true;
				}
			}
			if(!findticket){
				Logger.error("废票第三态,订单查询没有返回该车票的信息");
			}
		}
		return false;
	}

	public boolean cancelinsurance(String jsonString) {
		Date date = new Date();
		ReturninsuranceVO returninsuranceVO = null;
		Cancelinsurancerequest request = null;
//		Cancelinsuranceresponse response = null;
		try {
			returninsuranceVO = (ReturninsuranceVO) JsonUtil.readJson2Entity(jsonString, ReturninsuranceVO.class);
		} catch (Exception e) {
			LogUtil.logerror("网站请求格式错误,XML转换失败" + jsonString, e);
			ErrorMailUtil.sendMail("BRTTI0001", e);
			return false;
		}
		if(JPA.em().getTransaction().isActive()){
			JPA.em().getTransaction().commit();
		}
		request = returninsuranceVO.getRequestcontent();
//		response = returninsuranceVO.getResponsecontent();
		
		String netticketid = request.getNetticketid();
		
		Organization sellorg = queryOrganizationByCode(request.getPublicrequest().getAskorgcode());

		try {
			
			Insurance insurance = null;
			try {
				insurance=(Insurance)JPA.em().createQuery("select i from Insurance i where i.netticketid = :netticketid ").setParameter("netticketid", netticketid).getSingleResult();
			} catch (Exception e) {
				LogUtil.logerror("未找到电子票号为" + netticketid + "保单信息");
				ErrorMailUtil.sendMail("BRTTI0001", "未找到电子票号为" + netticketid + "保单信息");
				return false;
			}
			if(!JPA.em().getTransaction().isActive()){
				JPA.em().getTransaction().begin();
			}
			
			if(insurance !=null){
				insurance.updatetime = date;
				insurance.insurancestatus = "2";
				//更新保险状态
				insurance.save();
				InsuranceCancel insuranceCancel = new InsuranceCancel();
				insuranceCancel.id = insurance.id;
				insuranceCancel.insuranceid = insurance.id;
				insuranceCancel.netticketid = insurance.netticketid;
				insuranceCancel.departorgcode = insurance.departorgcode;
				insuranceCancel.departdate = insurance.departdate;
				insuranceCancel.cancelorgcode = sellorg.code;
				insuranceCancel.premium = insurance.premium;
				insuranceCancel.cancelname = request.getPublicrequest().getAskorgname();
				insuranceCancel.canceltime = date;
				insuranceCancel.cancelway = "0";
				insuranceCancel.cancelip = getServersaddressIp(sellorg.serversaddress);
				insuranceCancel.ticketoutlets = insurance.ticketoutlets;
				insuranceCancel.createtime = date;
				insuranceCancel.createby = 0;
				insuranceCancel.updatetime = date;
				insuranceCancel.updateby = 0;
			
				JPA.em().persist(insuranceCancel);
			}
			JPA.em().getTransaction().commit();
			finishMsg(jsonString ,new Date());
			return true;
		} catch (Exception e) {
			LogUtil.logerror("废票消费失败" + jsonString, e);
			if (!JPA.em().getTransaction().isActive()) {
				JPA.em().getTransaction().begin();
			}
			JPA.em().getTransaction().rollback();
			ErrorMailUtil.sendMail("BRTTI0001", e);
			return false;
		}	
	}
	
	
	@SuppressWarnings("unused")
	private String orderquery(String jsonString) {
		Orderqueryrequest orderqueryreq;
		Orderqueryresponse orderqueryres = new Orderqueryresponse();
		orderqueryres.setPublicresponse(PublicXmlUtil.newPublicresponse());
		try {
			try {
				orderqueryreq = (Orderqueryrequest) JsonUtil.readJson2Entity(jsonString, Orderqueryrequest.class);

			} catch (Exception e) {
				orderqueryres.getPublicresponse().setResultcode("NAODQR1000");
				orderqueryres.getPublicresponse().setResultmsg("网站请求格式错误");
				LogUtil.logerror("网站请求格式错误,XML转换失败" + jsonString, e);
				return PublicXmlUtil.toXml(orderqueryres);
			}
			Publicresponse pbres = checkPublicrequest(orderqueryreq.getPublicrequest(), "NDODQR2000", "NDODQR2001");
			if (!pbres.getResultcode().equals("0000")) {
				orderqueryres.getPublicresponse().setResultcode(pbres.getResultcode());
				orderqueryres.getPublicresponse().setResultmsg(pbres.getResultmsg());
				return PublicXmlUtil.toXml(orderqueryres);
			}

			if (isonline(orderqueryreq.getPublicrequest().getTargetorgcode()).equals("1")) {
				orderqueryres.getPublicresponse().setResultcode("NBODQR3000");
				orderqueryres.getPublicresponse().setResultmsg("无法连接" + orderqueryreq.getPublicrequest().getTargetorgcode() + "机构服务器");
				LogUtil.logerror("无法连接" + orderqueryreq.getPublicrequest().getTargetorgcode() + "机构服务器");
				return PublicXmlUtil.toXml(orderqueryres);
			}
			if (isonline(orderqueryreq.getPublicrequest().getTargetorgcode()).equals("2")) {
				orderqueryres.getPublicresponse().setResultcode("NBODQR3000");
				orderqueryres.getPublicresponse().setResultmsg("无法连接" + orderqueryreq.getPublicrequest().getTargetorgcode() + "机构服务器");
				LogUtil.logerror("无法连接" + orderqueryreq.getPublicrequest().getTargetorgcode() + "机构服务器");
				return PublicXmlUtil.toXml(orderqueryres);
			}

			List<Orderticket> ordertickets = null;
			try {
				String serversaddress = queryOrganizationByCode(orderqueryreq.getPublicrequest().getTargetorgcode()).serversaddress;
				InvokeService invokeService = invoke(orderqueryreq.getPublicrequest().getTargetorgcode());
				if (invokeService == null) {
					orderqueryres.getPublicresponse().setResultcode("NARDQR1001");
					orderqueryres.getPublicresponse().setResultmsg("获取调用接口失败");
					return PublicXmlUtil.toXml(orderqueryres);
				}
				Orderqueryresponse _orderqueryres = invokeService.orderquery(serversaddress, orderqueryreq);
				if (_orderqueryres == null) {
					orderqueryres.getPublicresponse().setResultcode("NARDQR1001");
					orderqueryres.getPublicresponse().setResultmsg("获取调用接口失败");
					return PublicXmlUtil.toXml(orderqueryres);
				}
				return PublicXmlUtil.toXml(_orderqueryres);
			} catch (Exception e) {
				// 请求调用失败
				orderqueryres.getPublicresponse().setResultcode("NARDQR1006");
				orderqueryres.getPublicresponse().setResultmsg("调用车站接口失败");
				LogUtil.logerror("调用车站接口失败" + jsonString, e);
				return PublicXmlUtil.toXml(orderqueryres);
			}

		} catch (Exception e) {
			LogUtil.logerror("订单查询失败：未知异常" + jsonString, e);
			orderqueryres.getPublicresponse().setResultcode("NAODQR1010");
			orderqueryres.getPublicresponse().setResultmsg("订单查询失败：未知异常");
			return PublicXmlUtil.toXml(orderqueryres);
		}
	}

	private String findParamValue(String code, Long orgid) {
		String sql = "";
		if (orgid != null && orgid != 0) {
			sql = sql + "select d.value from Parameter p ,Parameterorgdetail d " + "where d.parameterid = p.id  and p.code= '" + code + "' and d.orgid = " + orgid;
		} else {
			sql = sql + "select p.value from Parameter p  where p.code = '" + code + "'";
		}
		try {
			return JPA.em().createNativeQuery(sql).getSingleResult().toString();
		} catch (Exception e) {
			return "0";
		}
	}

	@WebMethod(exclude = true)
	private InvokeService invoke(String orgcode) {
		InvokeService invokeService = null;
		try {
			Organization org = (Organization) JPA.em().createQuery("select o from Organization o where o.code = :code").setParameter("code", orgcode).getSingleResult();

			String fullclassname = org.fullclassname;
			invokeService = (InvokeService) Class.forName(fullclassname).newInstance();
		} catch (Exception e) {
			LogUtil.logerror("orgcode：" + orgcode + "获取调用接口失败", e);
			return null;
		}
		return invokeService;
	}

	@WebMethod(exclude = true)
	private Publicresponse checkPublicrequest(Publicrequest pubreq, String code1, String code2) {
		Publicresponse publicresponse = new Publicresponse();
		publicresponse.setResultcode("0000");
		publicresponse.setResultmsg("SUCCESS");
		Organization sellorg = (Organization) JPA.em().createQuery("select o from Organization o where o.code = :code").setParameter("code", pubreq.getAskorgcode()).getSingleResult();

		if (sellorg == null) {
			publicresponse.setResultcode(code1);
			publicresponse.setResultmsg("未找到售票机构");
			LogUtil.logerror("未找到售票机构: " + pubreq.getAskorgcode());
			return publicresponse;
		}
		Organization departorg = (Organization) JPA.em().createQuery("select o from Organization o where o.code = :code").setParameter("code", pubreq.getTargetorgcode()).getSingleResult();
		if (departorg == null) {
			publicresponse.setResultcode(code2);
			publicresponse.setResultmsg("未找到发车机构");
			LogUtil.logerror("未找到发车机构: " + pubreq.getTargetorgcode());
			return publicresponse;
		}
		return publicresponse;
	}

	@WebMethod(exclude = true)
	private String isonline(String orgcode) {
		try {
			Organization org = (Organization) JPA.em().createQuery("select o from Organization o where o.code = :code").setParameter("code", orgcode).getSingleResult();
			return org.isonline;
		} catch (Exception e) {
			LogUtil.logerror("没查到orgcode为" + orgcode + "的机构表信息", e);
			return null;
		}
	}

	@WebMethod(exclude = true)
	private Double getReturnRate(Date datetime) {

		String minute = findParamValue("1106", null);
		int time = 120;
		try {
			time = Integer.parseInt(minute);
		} catch (Exception e) {
			LogUtil.logerror("数据库参数表中，1106号参数的值应该为整数分钟！", e);
		}
		Date stopreturntime = DateUtils.add(datetime, Calendar.MINUTE, time * -1);
		if (stopreturntime.before(new Date())) {
			LogUtil.logerror("超过设置退票时间，无法计算退票费");
			return 1.00d;
		}
		Date changeRate = DateUtils.add(datetime, Calendar.MINUTE, -120);
		String rate = null;
		if (changeRate.after(new Date())) {
			rate = findParamValue("1103", null);
		} else {
			rate = findParamValue("1104", null);
		}
		DecimalFormat df = new DecimalFormat(".00");
		Double ratefee = null;
		try {
			ratefee = df.parse(df.format(Double.parseDouble(rate) / 100)).doubleValue();
		} catch (Exception e) {
			LogUtil.logerror("退票手续费类型转换失败", e);
		}
		return ratefee;
		// return Double.parseDouble(rate)/100;//不保证返回正确的结果，有时间改成DecimalFormat
	}

	@WebMethod(exclude = true)
	private Double getReturnFee(double ticketPrice, Date datetime) {
		String rule = findParamValue("1105", null);
		double returnRate = getReturnRate(datetime);
		if (returnRate == 1.00) {
			LogUtil.logerror("超过设置退票时间，无法计算退票费！");
			// return 0d;
			return null;
		}
		if (returnRate > 1.00) {
			LogUtil.logerror("费率设置错误，无法计算退票费！");
			throw new RuntimeException("费率设置错误，无法计算退票费！");
		}
		Double returnFee = null;
		if ("1".equals(rule)) {
			returnFee = new BigDecimal(ticketPrice * returnRate).setScale(0, BigDecimal.ROUND_HALF_UP).doubleValue();
		} else if ("2".equals(rule)) {
			returnFee = Math.floor(ticketPrice * returnRate);
		} else if ("3".equals(rule)) {
			returnFee = Math.ceil(ticketPrice * returnRate);
		} else if ("4".equals(rule)) {
			// throw new RuntimeException("还没查好怎么写。。");
		}
		DecimalFormat df = new DecimalFormat(".00");
		try {
			returnFee = df.parse(df.format(returnFee)).doubleValue();
		} catch (ParseException e) {
			LogUtil.logerror("退票手续费类型转换失败", e);
		}
		return returnFee;
	}

	private Organization queryOrganizationByCode(String orgcode) {
		Organization organization = null;
		String sql = "select o from Organization o where o.isactive=1 and o.code='" + orgcode + "'";
		Query queryOrganization = JPA.em().createQuery(sql);
		try {
			organization = (Organization) queryOrganization.getSingleResult();
		} catch (Exception e) {

		}
		return organization;
	}


	private Orderqueryresponse getOrderResponse(String orderno, Publicrequest publicrequest, String netticketid) {
		Orderqueryrequest orderqueryrequest = new Orderqueryrequest();
		orderqueryrequest.setPublicrequest(publicrequest);
		orderqueryrequest.setOrderno(orderno);
		orderqueryrequest.setNetticketid(netticketid);
		orderqueryrequest.setTicketno(null);

		String requestJson = null;
		Orderqueryresponse orderqueryres = null;

		try {
			requestJson = JsonUtil.parseObject(orderqueryrequest);
		} catch (Exception e) {
			LogUtil.logerror("请求字符串格式错误,XML转换失败", e);
			return null;
		}

		String responseJson = orderquery(requestJson);

		try {
			orderqueryres = (Orderqueryresponse) XmlUtil.toBean(responseJson, Orderqueryresponse.class);
		} catch (Exception e) {
			LogUtil.logerror("订单查询应答字符串格式错误,XML转换失败", e);
			return null;
		}
		return orderqueryres;
	}

	public String getServersaddressIp(String serversaddress) {
		if (null == serversaddress)
			return null;
		int index = serversaddress.indexOf(":");
		if (index < 0) {
			return serversaddress;
		} else {
			return serversaddress.substring(0, index);
		}
	}

	public String getServersaddressPort(String serversaddress) {
		if (null == serversaddress)
			return null;
		int index = serversaddress.indexOf(":");
		if (index < 0) {
			return "3700";
		} else {
			return serversaddress.substring(index + 1);
		}
	}
	
	private void finishMsg(String jsonString, Date dealtime){
		long msghashid = FNVHash.hash64(jsonString);
		EntityManager em = JPA.newEntityManager();
		try {
			EntityTransaction transaction = em.getTransaction();
			transaction.begin();
			String FINISH_MSGSENDLOG = "update msgsendlog set dealed = :dealed,"
					+ " dealtime = :dealtime where msghashid = :msghashid";
			Query finishQuery = em.createNativeQuery(FINISH_MSGSENDLOG);
			finishQuery.setParameter("dealtime", new Timestamp(dealtime.getTime()));
			finishQuery.setParameter("dealed", true);
			finishQuery.setParameter("msghashid", msghashid);
			finishQuery.executeUpdate();
			em.getTransaction().commit();
		} catch (Exception e) {
			em.getTransaction().rollback();
			LogUtil.logerror("更新消息消费状态失败   消息msghashid  : "+msghashid, e);
		}finally{
			if(em.getTransaction().isActive()){
				em.getTransaction().commit();
			}
			if(em!=null){
				if(em.isOpen()){
					em.close();
				}
			}
		}
	}
	private Sellrequest changeParam(CenterSellRequest sellreq) {
		JSONObject json = JSONObject.fromObject(sellreq);
		json.remove("exchangefee");
		json.remove("isopenapiask");
		return (Sellrequest) JsonUtil.readJson2Entity(json.toString(), Sellrequest.class);
	}
	
}
